const express = require('express');
const router = express.Router();
const User = require('../models/user');

// 获取用户列表
router.get('/list', async (req, res) => {
	try {
		const { page = 1, pageSize = 10, username, role, status } = req.query;
		const query = {};

		if (username) {
			query.username = new RegExp(username, 'i');
		}
		if (role) {
			query.role = role;
		}
		if (status !== undefined) {
			query.status = status === 'true';
		}

		const total = await User.countDocuments(query);
		const list = await User.find(query)
			.select('-password')
			.skip((page - 1) * pageSize)
			.limit(Number(pageSize))
			.sort({ createdAt: -1 });

		res.status(200).json({
			code: 200,
			data: {
				list,
				total,
				page: Number(page),
				pageSize: Number(pageSize)
			}
		});
	} catch (error) {
		res.status(500).json({
			code: 500,
			message: '获取用户列表失败'
		});
	}
});

// 创建用户
router.post('/create', async (req, res) => {
	try {
		const { username, password, email, phone, role, status, remark } = req.body;

		// 检查用户名是否已存在
		const existingUser = await User.findOne({ username });
		if (existingUser) {
			return res.status(403).json({
				code: 403,
				message: '用户名已存在'
			});
		}

		const user = new User({
			username,
			password,
			email,
			phone,
			role,
			status,
			remark
		});

		await user.save();

		// 返回用户信息时排除密码
		const userWithoutPassword = user.toObject();
		delete userWithoutPassword.password;

		res.status(200).json({
			code: 200,
			data: userWithoutPassword
		});
	} catch (error) {
		res.status(500).json({
			code: 500,
			message: '创建用户失败'
		});
	}
});

// 更新用户
router.put('/:id', async (req, res) => {
	try {
		const { username, password, email, phone, role, status, remark } = req.body;

		// 检查用户是否存在
		const user = await User.findById(req.params.id);
		if (!user) {
			return res.status(404).json({
				code: 404,
				message: '用户不存在'
			});
		}

		// 检查用户名是否已被其他用户使用
		if (username !== user.username) {
			const existingUser = await User.findOne({ username });
			if (existingUser) {
				return res.status(403).json({
					code: 403,
					message: '用户名已存在'
				});
			}
		}

		// 更新用户信息
		if (username) user.username = username;
		if (password) user.password = password;
		if (email) user.email = email;
		if (phone) user.phone = phone;
		if (role) user.role = role;
		if (status !== undefined) user.status = status;
		if (remark) user.remark = remark;

		await user.save();

		// 返回用户信息时排除密码
		const userWithoutPassword = user.toObject();
		delete userWithoutPassword.password;

		res.status(200).json({
			code: 200,
			data: userWithoutPassword
		});
	} catch (error) {
		res.status(500).json({
			code: 500,
			message: '更新用户失败'
		});
	}
});

// 删除用户
router.delete('/:id', async (req, res) => {
	try {
		const user = await User.findById(req.params.id);
		if (!user) {
			return res.status(404).json({
				code: 404,
				message: '用户不存在'
			});
		}

		// 不允许删除管理员账号
		if (user.role === 'admin') {
			return res.status(403).json({
				code: 403,
				message: '不能删除管理员账号'
			});
		}

		await user.deleteOne();

		res.status(200).json({
			code: 200,
			message: '删除成功'
		});
	} catch (error) {
		res.status(500).json({
			code: 500,
			message: '删除用户失败'
		});
	}
});

module.exports = router;
